﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LastfmNet.Models;
using LastfmNet.Api;
using System.Globalization;

namespace LastfmNet
{
    public class LastfmSession
    {
        private Lastfm lastfmApi;
        private string sessionKey = null;
        private string apiSecret = null;
        private string apiKey = null;
        private string token = null;
        private bool authenticated = false;

        public LastfmSession(Lastfm lastfmApi, string apiKey, string apiSecret)
        {
            this.lastfmApi = lastfmApi;
            this.apiKey = apiKey;
            this.apiSecret = apiSecret;
        }

        public void Authenticate(string lastfmUsername, string lastfmPassword)
        {
            if (authenticated)
            {
                throw new LastfmNetException("You are already authenticated!");
            }
            string authToken = (lastfmUsername + (lastfmPassword.ToMD5())).ToMD5();
            this.token = authToken;
            Session session = lastfmApi.Auth.GetMobileSession(lastfmUsername, authToken);
            sessionKey = session.Key;
            if (!string.IsNullOrEmpty(sessionKey)) authenticated = true;
            else authenticated = false;
        }

        public string RequestAuthorizationFromTheUserURL()
        {
            this.token = lastfmApi.Auth.GetToken();
            return string.Format(CultureInfo.InvariantCulture, "http://www.last.fm/api/auth/?api_key={0}&token={1}", apiKey, this.token);
        }

        public void GetSession()
        {
            if (authenticated)
            {
                throw new LastfmNetException("You are already authenticated!");
            }
            if (string.IsNullOrEmpty(token))
            {
                throw new LastfmNetException("You must first request a token and the user must authorize it!");
            }
            Session session = lastfmApi.Auth.GetSession(token);
            sessionKey = session.Key;
            if (!string.IsNullOrEmpty(sessionKey)) authenticated = true;
            else authenticated = false;
        }

        public string SessionKey
        {
            get
            {
                return sessionKey;
            }
        }

        public string ApiSecret
        {
            get
            {
                return apiSecret;
            }
        }

        public string ApiKey
        {
            get
            {
                return apiKey;
            }
        }

        public string Token
        {
            get
            {
                return token;
            }
        }

        public bool Authenticated
        {
            get
            {
                return authenticated;
            }
        }
    }
}
